package com.gewe.wxChat.manager.strategy;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gewe.wxChat.api.base.GroupApi;
import com.gewe.wxChat.api.base.MessageApi;
import com.gewe.wxChat.model.dto.gewe.TextCallback;
import com.gewe.wxChat.model.entity.WxGroup;
import com.gewe.wxChat.model.entity.WxMember;
import com.gewe.wxChat.model.entity.WxTask;
import com.gewe.wxChat.model.enums.TaskStatusEnum;
import com.gewe.wxChat.model.enums.TaskTypeEnum;
import com.gewe.wxChat.service.WxGroupService;
import com.gewe.wxChat.service.WxMemberService;
import com.gewe.wxChat.service.WxTaskService;
import com.gewe.wxChat.utils.SanZhiUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class SanZhiStrategy implements JudgeStrategy {
    
    private static String[] yaoYueKeyWord={"邀约","短信","宝奇","两个链接","短信"};
    
    private static  String[] heTongKeyWord = {"签宝","合同","两个链接","e签","E签","短信"};
    

    private static final Logger logger = LoggerFactory.getLogger(SanZhiStrategy.class);
    
    @Resource
    private WxGroupService wxGroupService;
    
    @Resource
    private WxMemberService wxMemberService;
    
    @Resource
    private WxTaskService wxTaskService;
    @Override
    public void analysis(TextCallback textCallback){
        if(textCallback == null){
            return;
        }
        //插入到任务表中
        WxTask wxTask=new WxTask();
        //设置任务属性
        wxTask.setTaskType(TaskTypeEnum.LLK_TASK.getValue());
        wxTask.setTaskStatus(0); 
        
        wxTask.setAppId(textCallback.getAppId());
        wxTask.setWxId(textCallback.getWxId());
        wxTask.setFromUserName(textCallback.getFromUserName());
        wxTask.setToUserName(textCallback.getToUserName());
        wxTask.setMsgType(textCallback.getMsgType());
        wxTask.setContent(textCallback.getContent());
        wxTask.setMsgCreateTime(textCallback.getCreateTime());
        wxTask.setNewMsgId(textCallback.getNewMsgId());
        //拿到这个newMagId
        Long newMsgId=textCallback.getNewMsgId();
        
        //插入成功，代表这个任务是第一次插入，做到去重作用
        if(!wxTaskService.save(wxTask)){
            return;
        }
        
       String contentText=textCallback.getContent();
       String fromUserNameText=textCallback.getFromUserName();
       String appId=textCallback.getAppId();
        
       //获取@对象
        String ats="";
        String[] parts = contentText.split(":", 2);
        //在微信群内才需要@别人
        if(fromUserNameText.contains("@chatroom") && parts.length > 0){
            ats = contentText.split(":", 2)[0];
        }
        //是否是邀约或者合同 或者代收协议
        if(isYaoyue(contentText) || isHetong(contentText) || contentText.contains("代收协议")){
            List<String> formIdList=getKeyWordList(contentText);
            if(CollectionUtils.isEmpty(formIdList) || formIdList.size()==0){
                return;
            }
            logger.info("需求单号是:"+formIdList);
            
            StringBuilder builder=new StringBuilder();
            for(String formId:formIdList){
                String result=start(formId,contentText);
                //发送消息给对应的人
                builder.append(result);
                builder.append("\n");
            }
            sendMsg(appId,fromUserNameText,builder.toString(),ats,newMsgId);
        }
        
        //是否推送运单
        if(contentText.contains("【支付问题】")){
            String formId=getKeyWord(contentText);
            String result="https://www.lingluke.cn/api/orderxcx/zhiFuYaJinNotifyHand?formId="+formId;
            sendMsg(appId,fromUserNameText,result,ats,newMsgId);
        }
        
    }

    public String start(String formId,String context){
        StringBuilder builder=new StringBuilder();
       
        //获取邀约
        HashMap<String,Object> map = SanZhiUtils.wangHuoYaoyue(formId);
        Boolean isWangHuo=(Boolean)map.get("isWangHuo");
        //是 非网货运单
        if( ! isWangHuo){
            //查询全部运单
            map = SanZhiUtils.yunDanList(formId);
        }
        String frtId=map.get("frtId").toString();
        
        //判断是否有代收协议
        if(context.contains("代收协议")){
            builder.append("【代收协议】https://www.lingluke.cn/wanghuo/baoQi/signing?frtId="+frtId+"&flag=2");
            builder.append("\n");
        }
        
        //拼接进度状态
        if(map.get("stepRemark") !=null){
            builder.append(map.get("stepRemark").toString());
            builder.append("\n");
        }
        //拼接邀约
        if(map.get("yaoyue") != null &&isYaoyue(context)){
            builder.append(map.get("yaoyue").toString());
            builder.append("\n");
        }
        //拼接合同
        if(isHetong(context)){
            //获取合同
            String heTong=SanZhiUtils.getHeTong(frtId);
            builder.append(heTong);
        }
        //运单
        String billFormId=map.get("billFormId").toString();
        //司机
        String driverName=map.get("carrierName") != null ? map.get("carrierName").toString() : "";
        return billFormId+"   "+driverName+"  "+builder.toString();
    }
    

    public  boolean isYaoyue(String contentText) {
        for (String sensitiveWord : yaoYueKeyWord) {
            if (contentText.contains(sensitiveWord)) {
                // 找到敏感词，返回true
                return true;
            }
        }
        // 没有找到敏感词，返回false
        return false;
    }

    public  boolean isHetong(String contentText) {
        for (String sensitiveWord : heTongKeyWord) {
            if (contentText.contains(sensitiveWord)) {
                // 找到敏感词，返回true
                return true;
            }
        }
        // 没有找到敏感词，返回false
        return false;
    }
    
    
    //发送内容给对应的人
    public void sendMsg(String appId,String toWxid,String content,String ats,Long newMsgId){
        
        if(toWxid.contains("@chatroom")){
            if(StringUtils.isNotBlank(ats)){
                LambdaQueryWrapper<WxGroup> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(WxGroup::getChatRoomId,toWxid);
                WxGroup wxGroup=wxGroupService.getOne(queryWrapper);
                //查看这个微信群是不是有记录，没有记录要去查询
                if(wxGroup == null){
                    ((SanZhiStrategy) AopContext.currentProxy()).getGroupMember(appId,toWxid);
                }
                //寻找消息发送人，重新拼接content
                LambdaQueryWrapper<WxMember> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(WxMember::getWxId,ats);
                lambdaQueryWrapper.eq(WxMember::getChatRoomId,toWxid);
                WxMember wxMember=wxMemberService.getOne(lambdaQueryWrapper);
                if(wxMember != null){
                    if(StringUtils.isNotEmpty(wxMember.getDisplayName())){
                        content="@"+wxMember.getDisplayName()+" "+content;
                    }else if(StringUtils.isNotEmpty(wxMember.getNickName())) {
                        content="@"+wxMember.getNickName()+" "+content;
                    }
                } 
            }
        }
        //可以邀约有链接，但是合同没有，这里需要处理一下
        if(content.contains("5分钟后重发") && content.contains("http")){
            content="5分钟后重发";
        }
//        JSONObject jsonObject=MessageApi.postText(appId, toWxid, content,ats);
//        logger.info("微信发送消息返回结果"+jsonObject);
//
//        //判断任务是否执行成功，并且是否需要重发
//        Integer code=(Integer) jsonObject.get("ret");
//        if(code == 200 && !content.contains("5分钟后重发")){
//            UpdateWrapper<WxTask> updateWrapper=new UpdateWrapper<>();
//            updateWrapper.eq("newMsgId",newMsgId);
//            updateWrapper.eq("appId",appId);
//            updateWrapper.set("taskStatus", TaskStatusEnum.YiChuLi.getValue());
//            wxTaskService.update(updateWrapper);
//        }else {
//            UpdateWrapper<WxTask> updateWrapper=new UpdateWrapper<>();
//            updateWrapper.eq("newMsgId",newMsgId);
//            updateWrapper.eq("appId",appId);
//            updateWrapper.set("taskStatus",TaskStatusEnum.DaiChuLi.getValue());
//            wxTaskService.update(updateWrapper);
//        }
    }

    //获取关键字 ，也就是需求单号
    public List<String> getKeyWordList(String context){
        List<String> list=new ArrayList<>();
        while (true){
            String keyWord=getKeyWord(context);
            if(StringUtils.isNotBlank(keyWord)){
                list.add(keyWord);
                context=context.replace(keyWord,"");
            }else {
                break;
            }
        }
        return list;
    }
    
    //获取关键字，也就是需求单号
    public String getKeyWord(String context){
        //判断有没有网址
        if(context.contains("http://") || context.contains("www.") || context.contains("https://")){
            return "";
        }
        // 正则表达式，匹配以24开头的连续10位数字，紧随其后的是#和一个数字（如果存在）
        String regex = "2[45]\\d{8}(?:#\\d)?";
        // 创建Pattern对象
        Pattern pattern = Pattern.compile(regex);
        // 创建matcher对象
        Matcher matcher = pattern.matcher(context);
        // 如果找到匹配
        if (matcher.find()) {
            // 获取匹配的完整字符串
            String matched = matcher.group();
            // 检查是否有#和随后的数字
            String formId = matched;
            int hashIndex = matched.indexOf('#');
            if (hashIndex != -1 && hashIndex + 1 < matched.length()) {
                // 如果存在#和随后的数字，则只取#和第一个数字
                formId = matched.substring(0, hashIndex + 2);
            }
            return formId;
        } else {
            return "";
        }
    }
    
    //获取微信群成员
    @Transactional(rollbackFor = Exception.class)
    public void getGroupMember(String appId,String chatroomId){
        JSONObject jsonObject= GroupApi.getChatroomInfo(appId, chatroomId);
        HashMap<String, Object> dataMap = (HashMap<String, Object>) jsonObject.get("data");
        //设置微信实体类
        WxGroup wxGroup=new WxGroup();
        wxGroup.setChatRoomId(chatroomId);
        wxGroup.setChatRoomNotify(dataMap.get("chatRoomNotify") != null ? (Integer) dataMap.get("chatRoomNotify") : null);
        wxGroup.setChatRoomOwner(dataMap.get("chatRoomOwner") != null ? (String) dataMap.get("chatRoomOwner") : null);
        wxGroup.setNickName(dataMap.get("nickName") != null ? (String) dataMap.get("nickName") : null);
        wxGroup.setPyInitial(dataMap.get("pyInitial") != null ? (String) dataMap.get("pyInitial") : null);
        wxGroup.setQuanPin(dataMap.get("quanPin") != null ? (String) dataMap.get("quanPin") : null);
        wxGroup.setRemark(dataMap.get("remark") != null ? (String) dataMap.get("remark") : null);
        wxGroup.setRemarkPyInitial(dataMap.get("remarkPyInitial") != null ? (String) dataMap.get("remarkPyInitial") : null);
        wxGroup.setRemarkQuanPin(dataMap.get("remarkQuanPin") != null ? (String) dataMap.get("remarkQuanPin") : null);
        wxGroup.setSex(dataMap.get("sex") != null ? (Integer) dataMap.get("sex") : null);
        wxGroup.setSmallHeadImgUrl(dataMap.get("smallHeadImgUrl") != null ? (String) dataMap.get("smallHeadImgUrl") : null);
        
        List<HashMap<String,Object>> memberList=(List<HashMap<String, Object>>) dataMap.get("memberList");
        List<WxMember> wxMembers=new ArrayList<>();
        for(HashMap<String,Object> map:memberList){
            WxMember wxMember=new WxMember();
            wxMember.setWxId(map.get("wxid") != null ? (String) map.get("wxid") : null);
            wxMember.setBigHeadImgUrl(map.get("bigHeadImgUrl") != null ? (String) map.get("bigHeadImgUrl") : null);
            wxMember.setDisplayName(map.get("displayName") != null ? (String) map.get("displayName") : null);
            wxMember.setNickName(map.get("nickName") != null ? (String) map.get("nickName") : null);
            wxMember.setSmallHeadImgUrl(map.get("smallHeadImgUrl") != null ? (String) map.get("smallHeadImgUrl") : null);
            wxMember.setChatRoomId(chatroomId);
            wxMembers.add(wxMember);
        }

        try {
            wxGroupService.save(wxGroup);
            //更新微信用户群
            wxMemberService.saveMemberByWxIdAndChatRoomId(wxMembers);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    //推送运单
    public String pushWayBill(String formId){
        //去 网货接口查询运单
        HashMap<String,Object> map = SanZhiUtils.wangHuoYaoyue(formId);
        Boolean isWangHuo=(Boolean)map.get("isWangHuo");
        if( ! isWangHuo){
            //查询全部运单
            return "非网货运单";
        }
//        ShenTong(150,"神通") 
//        BaoQi(160,"宝奇")
//        HuaNing(170, "华甯")
        Integer whSourceType=(Integer)map.get("whSourceType");
        String frtId=(String)map.get("frtId");
        if(whSourceType == 150 || whSourceType == 160 || whSourceType == 170){
            return SanZhiUtils.pushWayBill(frtId);
        }
        return "";
    }
}
